<template>
  <div class="base-container" id="main">
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <div class="apply-form">
      <t-form ref="form" :key="activeForm" :colon="true" class="step-form" :data="formData" :rules="rules"
        labelWidth="150px">
        <t-row style="flex: 1">
          <t-col :span="12">

            <t-card class="step-card" size="small" title="推广基本信息">
              <t-form-item label="成果类别" name="achievementType">
                <t-select style="width: 390px" @change="onTypeChange" :options="dict.type.achievement_type"
                  v-model="formData.achievementType">
                </t-select>
              </t-form-item>
              <t-form-item v-if="formData.achievementType" label="成果名称" name="name">
                <t-select v-model="formData.name" @change="onNameChange" filterable placeholder="请输入成果名称"
                  :loading="nameLoading" @search="remoteNameMethod" :options="nameOptions" style="width: 390px" />
              </t-form-item>

              <t-form-item label="研发单位" name="createCompany">
                <t-tree-select @change="(val, content) => { formData.createCompanyId = content.node.data.id; }"
                  v-if="formData.isInnerCompany === '1'" style="width:390px" clearable filterable
                  :treeProps="{ keys: { value: 'label' } }" v-model="formData.createCompany" :data="deptMenuOptions"
                  placeholder="选择单位">
                  <div slot="tips">搜索不到请切换外部单位后手输</div>
                  <template #label>
                    <t-switch size="medium" v-model="formData.isInnerCompany" :label="['内部', '外部']"
                      :customValue="['1', '0']"
                      @change="() => { formData.createCompany = ''; formData.createCompanyId = null; }"></t-switch>
                  </template>
                </t-tree-select>
                <t-select v-else v-model="formData.createCompany" creatable filterable placeholder="请输入"
                  @change="(val, content) => { formData.createCompanyId = content.option?.id; }" :loading="companyLoading"
                  @search="remoteCompanyMethod" :options="companyOptions" @create="createCompanyOptions"
                  style="width: 390px;display: inline-block">
                  <template #label>
                    <t-switch size="medium" v-model="formData.isInnerCompany" :label="['内部', '外部']"
                      :customValue="['1', '0']"
                      @change="() => { formData.name = ''; formData.createCompanyId = null; }"></t-switch>
                  </template>
                </t-select>
              </t-form-item>
              <t-form-item label="验收时间" name="accepentDate">
                <t-date-picker clearable style="width: 390px" v-model="formData.accepentDate"></t-date-picker>
              </t-form-item>
              <!--          <t-form-item label="备注" name="note">-->
              <!--            <t-textarea v-model="formData.note" :autosize="{ minRows: 5 }" placeholder="请输入您的备注"/>-->
              <!--          </t-form-item>-->
            </t-card>
            <t-card class="step-card" size="small" title="推广项目列表">
              <t-form-item :show-error-message="false" name="extendLists">
                <extend-project ref="extend-project" v-model="formData.extendLists" :editOpen="true"></extend-project>
              </t-form-item>
            </t-card>
          </t-col>
        </t-row>
        <t-row style="text-align: center;margin-top: 20px">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{
                applyLoading ? '提交中...' : '暂存'
              }}
              </t-button>
              <t-button theme="primary" :loading="applyLoading" @click="onSubmit(2)">{{
                applyLoading ? '提交中...' : '提交'
              }}
              </t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import FileUpload from "@/components/FileUpload/index.vue";
import ExtendProject from "./components/extend-project.vue";

export default {
  name: "extent-apply",
  dicts: ['achievement_type'],
  components: {
    FileUpload,
    ExtendProject
  },
  data () {
    return {
      companyLoading: false,
      deptMenuOptions: [],
      companyOptions: [],
      nameLoading: false,
      nameOptions: [],
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      objId: null,
      taskId: null,
      applyLoading: false,
      isCommit: false,
      activeForm: 0,
      formData: {
        name: '',
        achievementType: '',
        createCompany: '',
        createCompanyId: null,
        extendStatus: '',
        allInvestment: '',
        applyDate: '',
        allEfficiency: '',
        accepentDate: '',
        note: '',
        achievementId: null,
        isInnerCompany: '1',
        extendLists: []
      },
      rules: {
        name: [{ required: true, message: "成果名称不能为空" }],
        applyDate: [{ required: true, message: "应用时间不能为空" }],
        achievementType: [{ required: true, message: "成果类别不能为空" }],
        createCompany: [{ required: true, message: "研发单位不能为空" }],
        accepentDate: [{ required: true, message: "验收时间不能为空" }],
      },
    }
  },
  created () {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("缺少id");
      return false;
    }
    this.taskId = taskId;
    this.getObj();
    this.getDeptTreeSelect();
  },
  methods: {
    onTypeChange (index) {
      this.formData.name = ''
      if (index == 1) {
        // 论文
        this.$api.cgzh.thesis.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.name,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else if (index == 2) {
        // 专利
        this.$api.cgzh.patent.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.name,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else if (index == 3) {
        // 著作
        this.$api.cgzh.treatise.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.name,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else if (index == 4) {
        // 软件著作权
        this.$api.cgzh.copyright.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.name,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else if (index == 5) {
        // 获奖
        this.$api.cgzh.awards.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.name,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else if (index == 6) {
        // 标准
        this.$api.bzh.standard.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.projectName,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else if (index == 7) {
        // 工法
        this.$api.cgzh.gf.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.name,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else if (index == 8) {
        // 其他
        this.$api.cgzh.other.list({ pageNum: 1, pageSize: 10000 }).then(response => {
          this.nameOptions = response.rows.map(val => ({
            ...val,
            label: val.name,
            value: val.id,
          }));
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },
    getObj () {
      this.$api.cgzh.extend.get(this.taskId).then(response => {
        if (response.data) {
          Object.assign(this.formData, response.data);
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getDeptTreeSelect (id) {
      this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    createCompanyOptions (value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod (search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({ deptName: search }).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onNameChange (val, content) {
      this.formData.achievementId = content.option.id;
      this.formData.name = content.option.name || content.option.projectName;
    },
    remoteNameMethod (search) {
      this.nameLoading = true;
      this.$api.cgzh.achievementIndex({ name: search, achievementType: this.formData.achievementType }).then(response => {
        this.nameOptions = response.data.map(val => ({
          ...val,
          label: val.name,
          value: val.name,
        }));
        this.nameLoading = false;
      }).catch((e) => {
        this.nameLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit (type) {
      if (type === 1) {
        this.$refs.form.validate({
          fields: ['name']
        }).then((validateResult) => {
          if (validateResult === true) {
            this.applyLoading = true;
            if (!this.formData.id) {
              this.$api.cgzh.extend.add(this.formData).then(response => {
                this.formData.id = response.data.id;
                this.applyLoading = false;
                this.$message.success('暂存成功');
                this.close();
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.cgzh.extend.update(this.formData).then(response => {
                this.applyLoading = false;
                this.$message.success('暂存成功');
                this.close();
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })

      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            const isValidate = this.$refs["extend-project"].checkData()
            if (!isValidate) {
              return false;
            }
            this.applyLoading = true;
            if (!this.formData.id) {
              this.$api.cgzh.extend.add(this.formData).then(response => {
                this.formData.id = response.data.id;
                this.applyLoading = false;
                this.$message.success('提交成功');
                this.close();
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.cgzh.extend.update(this.formData).then(response => {
                this.applyLoading = false;
                this.$message.success('提交成功');
                this.close();
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }
    },
    close () {
      this.$tab.closeOpenPage({ path: `/cgzh/extend/extend-my` });
    },
  }
}
</script>

<style lang="less" scoped>
.base-container {
  display: flex;
  flex-direction: column;
}

.step-form {
  padding: 0 24px;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
